package whisper.service.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import whisper.common.support.response.WebResponseCode;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by JT on 2018/5/31
 */
@RestController
public class JsonErrorHandler extends BasicErrorController {

    private static final String ERROR_PATH = "/error";

    public JsonErrorHandler() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);

        if (StringUtils.isNotBlank(String.valueOf(body.get("exception")))) {
            body.put("code", WebResponseCode.CODE_ERROR);
            body.remove("timestamp");
            body.remove("status");
            body.remove("error");
            body.remove("exception");
            body.remove("path");
        }
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
